package com.steak.system.util;

import com.auth0.jwt.JWT;
import com.steak.system.pojo.dto.UserDTO;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {
    //创建jwt
    public static String createJWT(long expirationDate , UserDTO user){
        //签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //生成Jwt时间
        long jwtTime = System.currentTimeMillis();
        Date date = new Date(jwtTime);

        //创建payload私有声明
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        map.put("userName",user.getUserName());
        map.put("password",user.getPassword());
        map.put("role",user.getRoles());
        //生成签名的时候使用的密钥secret
        String key = user.getPassword();
        //签发人
        String subject = user.getUserName();
        //为payload添加各种标准
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(map)
                .setId(UUID.randomUUID().toString().replace("_",""))
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key.getBytes());
        if (expirationDate >= 0){
            long expDate = jwtTime + expirationDate;
            Date exp = new Date(expDate);
            jwtBuilder.setExpiration(exp);
        }
        return jwtBuilder.compact();
    }

    //Token解密
    public static Claims decryptJWT(String token , UserDTO user){
        //签名密钥
        String key = user.getPassword();
        Claims claims = Jwts.parser().setSigningKey(key)
                //需要解析的jwt
                .parseClaimsJws(token).getBody();
        return claims;
    }

    //验证token
    public static  Boolean checkJWT(String token , UserDTO user){
        //签名密钥
        String key = user.getPassword();
        try {
            String keyNew = JWT.decode(token).getClaim("password").asString();
            if (key.equals(keyNew)){
                return true;
            }
        }catch (RuntimeException e){
            e.printStackTrace();
        }
        return false;
    }
}
